package leetcode.editor.cn;

import java.util.ArrayList;
import java.util.List;

public class _22_GenerateParentheses {
    public static void main(String[] args) {
        Solution solution = new _22_GenerateParentheses().new Solution();
        List<String> strings = solution.generateParenthesis(3);
        for (String string : strings) {
            System.out.println(string);
        }
    }

    //leetcode submit region begin(Prohibit modification and deletion)

    class Solution {
        // left 为剩余的左括号个数, right 为剩余的右括号个数, 必须保证 left <= right
        private void backtrack(List<String> list, StringBuilder path, int left, int right) {
            if (left == 0 && right == 0) {
                list.add(path.toString());
                return;
            }
            if (left == right) {
                path.append("(");
                backtrack(list, path, left - 1, right);
                path.deleteCharAt(path.length() - 1);
            } else if (left < right) {
                if (left > 0) {
                    path.append("(");
                    backtrack(list, path, left - 1, right);
                    path.deleteCharAt(path.length() - 1);
                }
                if (right > 0) {
                    path.append(")");
                    backtrack(list, path, left, right - 1);
                    path.deleteCharAt(path.length() - 1);
                }

            }
        }

        public List<String> generateParenthesis(int n) {
            List<String> res = new ArrayList<>();
            backtrack(res, new StringBuilder(), n, n);
            return res;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}